// pages/confirmorder/confirmorder.js
const app=getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    user:{},
    addr:{
      name:'',
      phone:'',
      addr:''
    },
    types:[
      {id:'1',img:"/images/weixin.png",typeName:"微信支付",checked:"true"},
      {id:'2', img:"/images/xxzf.png", typeName: "线下支付", }
    ],
    tableid:'',
    cart:[],
    food:[],
    znum:0,
    zprice:0,
    preafterprice:0,
    checked1:false,
    pstype:'1',
    textareavalue: '',
    phonevalue:'',
    namevalue:'',
    coupon:{},
    points:{},
    integral: 0,
    integralpri:0,
    // yhq:{
    //   id:null,
    //   name:'不使用优惠券',
    //   pri:0
    // },
    orderdd:{},//提交的时候的订单
    bool:false,
  },
  radioChange: function (e) {
    console.log(e,'支付')
    this.setData({
      pstype: e.detail.value
    })
  },
  /*积分 */
  intejral:function(e){
    this.setData({
      checked1: !this.data.checked1
    })
    // this.preafterprice();
    // if (this.data.checked1) {
    //   this.jisuan()
    // }
    this.jisuan()
    
  },
  jisuan:function(){
    var that = this
    var zprice = that.data.zprice
    var integralpri = that.data.integralpri
    var noprice = zprice - integralpri
    that.setData({
      nowPrice:noprice
    })
    if (that.data.checked1==false){
      that.setData({
        nowPrice: zprice
      })
    }
  },
  textareachange:function(e){
    this.setData({
      textareavalue: e.detail.value
    })
  },
  phoneValue:function(e){
    this.setData({
      phonevalue: e.detail.value
    })
  },
  nameValue:function(e){
    this.setData({
      namevalue: e.detail.value
    })
    console.log(e)
  },
  addr: function () {
    var that = this;
    wx.chooseAddress({
      success: function (res) {
        that.setData({
          'addr.name': res.userName,
          'addr.phone': res.telNumber,
          'addr.addr': res.provinceName + res.cityName + res.countyName + res.detailInfo,
        })
      },
      fail: function (res) {
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.address']) {
              wx.authorize({
                scope: 'scope.address',
                success(res) {
                },
                fail: function (res) {
                  wx.openSetting({
                    success: (res) => {
                      if (!res.authSetting["scope.address"]) {
                        wx.showModal({
                          title: '提示',
                          content: '通讯地址授权失败，不能使用外卖',
                          showCancel: false,
                          success: function (res) {
                            if (res.confirm) {
                              that.setData({
                                pstype: 1
                              })
                            }
                          }
                        })
                      }
                    }
                  })
                }
              })
            }
          }
        })
      }
    })
  },
  /*jifen*/
  integral:function(e){

    var that=this;
    wx.request({
      url: app.globalData.directory + 'api/v2/pay/getUserPoints',
      method: 'POST',
      data: { price: wx.getStorageSync('priceszong') },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data.data.points, 'POINTSSSSSSSSSSSSS')
        that.setData({
          integral: res.data.data.points,
          integralpri: res.data.data.price
        })
      }
    })
    console.log(that.data.points,'那个积分')
    if (!that.data.points) return false;
  },
  
  /*总的价格数量 */
  znumprice: function () {
    var znum = 0;
    var zprice = 0;
    this.data.cart.forEach(function (item, index) {
      znum += item.num
      zprice += item.price * item.num
    })
    if (znum > 99) {
      znum = '99+'
    }
    zprice=parseInt(zprice*100)/100
    this.setData({
      znum: znum,
      zprice: zprice,
    })
    wx.setStorageSync('priceszong',zprice)
  },

  /*优惠后的价格*/
  preafterprice:function(){

    var that=this;
    var order={};
    var food=[];
    var points=null;
    var yhqid=null;
    var pstype = that.data.pstype
    that.data.cart.forEach(function(item){
      var spec='';
      if (item.type==1){
        item.specidac.forEach(function (item) {
          spec+='_'+item;
        })
      }
      food.push({ food_id:item.goodid,spec_item:spec,count:item.num})
    })
   
    if(that.data.checked1){
      points = that.data.integral;      
    }
     console.log(points,'我是积分吗')
    if (parseInt(points)) {
      order = {
        price: that.data.zprice,
        true_price: that.data.preafterprice,
        note: that.data.textareavalue,
        phone: that.data.addr.phone,
        food: food,
        type: parseInt(that.data.pstype),
        address: that.data.addr.addr,
        name: that.data.addr.name,
        points:points
      }
    } else {
      order = {
        price: that.data.zprice,
        true_price: that.data.preafterprice,
        note: that.data.textareavalue,
        phone: that.data.addr.phone,
        food: food,
        type: parseInt(that.data.pstype),
        address: that.data.addr.addr,
        name: that.data.addr.name,
      }
    }
    if(pstype =='2'){
      order.phone = that.data.phonevalue
      order.name  = that.data.namevalue
      order.address = 'null'
    }
    // if (pstype == "2" && parseInt(points)) {
    //   order = {
    //     price: that.data.zprice,
    //     true_price: that.data.preafterprice,
    //     note: that.data.textareavalue,
    //     phone: that.data.phonevalue,
    //     food: food,
    //     type: parseInt(that.data.pstype),
    //     name: that.data.namevalue,
    //     points:points
    //   }
    // } else {
    //   order = {
    //     price: that.data.zprice,
    //     true_price: that.data.preafterprice,
    //     note: that.data.textareavalue,
    //     phone: that.data.phonevalue,
    //     food: food,
    //     type: parseInt(that.data.pstype),
    //     name: that.data.namevalue,
    //   }
    // }
   
    that.setData({
      orderdd:order
    })
    wx.request({
      url: app.globalData.directory + 'api/v2/pay/handle_price',
      method:'POST',
      data: order,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.status == 'ok') {
          that.setData({
            preafterprice: res.data.data,
            'orderdd.true_price': res.data.data
          })
          if (that.data.bool) {
            console.log(that.data.orderdd);
            that.pay();
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000,
          })
          if(pstype =="2"){
            setTimeout(function(){
              wx.navigateTo({
                url: '../newBindPhone/newBindPhone',
              })
            },3000)
          }
        }
      }
    })
  },
  /*支付 */
  pay:function(){
    var that = this;
    var pstype = that.data.pstype
    wx.request({
      url: app.globalData.directory + 'api/v2/pay/order_pay',
      method: 'POST',
      data: that.data.orderdd,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        if (pstype == "1") {
          console.log(res,'/*/**/*/*/*/')
          if (res.data.status == 'ok') {
            if (res.data.msg == 'success') {
              wx.requestPayment({
                'timeStamp': res.data.data.timestamp,
                'nonceStr': res.data.data.nonceStr,
                'package': res.data.data.package,
                'signType': res.data.data.signType,
                'paySign': res.data.data.paySign,
                'success': function (res) {
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '../dingdan/dingdan?id=2',
                    })
                  }, 1000)
                },
                'fail': function (res) {
                  console.log(res)
                  wx.showToast({
                    // title: res.errMsg,
                    title: '未付款',
                    icon: 'none',
                    duration: 2000,
                  })
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '../dingdan/dingdan?id=1',
                    })
                  }, 1000)
                }
              })
            }
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000,
            })
          }
        }else{
          wx.showToast({
            // title: res.errMsg,
            title: '线下支付，商家正在受理',
            icon: 'none',
            duration: 2000,
          })
          setTimeout(function () {
            wx.switchTab({
              url: '../order/order',
            })
          }, 1000)
         
        }







      }
    })
  },
  /*提交表单 */
  bindsub:function(){
    this.setData({
      bool:true
    })
    // if (this.data.bool) {
    //   this.pay();
    //   // that.pay();
    // }
    this.preafterprice()
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (option) {
    var that = this;
    this.setData({
      cart: wx.getStorageSync('cart'),
      // tableid: app.globalData.tableid,
      // coupon: app.globalData.coupon,
      points: app.globalData.points,
      // user:app.globalData.user
    })
    console.log(app.globalData.points,'积分')
    
    wx.request({
      url: app.globalData.directory + 'api/v2/getCarGoods',
      method:"POST",
      data: { car: wx.getStorageSync('shopcar') },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.status == 'ok') {
          that.setData({
            foods: res.data.data
          })
        } else {
          wx.showToast({
            title: '请求失败,请重试',
            icon: 'none',
            duration: 2000,
          })
        }
      }
    })
    
    this.znumprice();
    this.integral();
    // this.preafterprice()
    this.jisuan();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that=this;
    if (parseInt(app.globalData.choosewelfare) == 0) {
      that.setData({
        'yhq.id': null,
        'yhq.name': '不使用优惠券',
        'yhq.pri': 0,
      })
      return false;
    }
    if (parseInt(app.globalData.choosewelfare)) {
      that.data.coupon.data.forEach(function (item, index) {
        if (item.id == app.globalData.choosewelfare) {
          that.setData({
            'yhq.id': item.id,
            'yhq.name': item.name,
            'yhq.pri': item.amount_cash,
          }) 
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})